android http json

使用Gson库


Step1: download Gson jar file

goto https://github.com/google/gson

Gson Download downloads at Maven Central

step2: To use Gson in Android

1) copy jar to app\libs (物理方式复制进入)

2) app->build.gradle文件中添加

dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}

ps:  错误处理

错误1:不能导入

ps: 点击alt+enter import class 无效时,点击alt+enter弹出菜单中gradle sync

错误2: Program type already present: com.google.gson.FieldNamingStrategy

dependencies {

configurations {
all*.exclude group: 'com.google.code.gson'
}

step 3 : 使用HttpURLConnection + Gson 示例

package com.qtechnix.hellowordl2;

import android.util.Log;
import com.google.gson.Gson;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

public class HttpJson {

public void HttpJson() {

}

public String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "/n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}

public Map<String, String> execute(String urlStr, String method, String... params) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;

try {

String domain = "";
String member_req_token_url = "";
// read responseURLEncoder.encode(para, "GBK");
String urlWithParams = domain + member_req_token_url + "?userName=" + java.net.URLEncoder.encode(params[0], "utf-8") + "&password=" + params[1];

URL url = new URL(urlStr);//urlWithParams);
urlConnection = (HttpURLConnection) url.openConnection();

//optional request header
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

//optional request header
urlConnection.setRequestProperty("Accept", "application/json");

// for Get request
urlConnection.setRequestMethod(method);//"GET" | "POST";
int statusCode = urlConnection.getResponseCode();

// 200 represents HTTP OK
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertStreamToString(inputStream);
Gson gson = new Gson();
Map<String, String> resultMap = gson.fromJson(response, Map.class);
if (resultMap != null && resultMap.size() > 0) {
Log.i("gmx", "please check the map with key");
}
return resultMap;
//UserDto dto = gson.fromJson(response, UserDto.class);
//if (dto != null && dto.getToken() != null) {
// Log.i("token", "find the token = " + dto.getToken());
//}
//return dto;
}
else {

}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}

public Map<String, String> execute(String urlStr, String method, Map<String, String> dto) {
InputStream inputStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(urlStr);
urlConnection = (HttpURLConnection) url.openConnection();

// optional request header
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");

// optional request header
urlConnection.setRequestProperty("Accept", "application/json");

//dto.setCreator(java.net.URLEncoder.encode(dto.getCreator(), "utf-8"));

// for Get request
urlConnection.setRequestMethod(method);//"POST");
urlConnection.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(urlConnection.getOutputStream());
Gson gson = new Gson();
String jsonString = gson.toJson(dto);
wr.writeBytes(jsonString);
wr.flush();
wr.close();
// try to get response
int statusCode = urlConnection.getResponseCode();
if (statusCode == 200) {
inputStream = new BufferedInputStream(urlConnection.getInputStream());
String response = convertStreamToString(inputStream);
Map<String, String> resultMap = gson.fromJson(response, Map.class);
if (resultMap != null && resultMap.size() > 0) {
Log.i("applyDesigner", "please check the map with key");
}
return resultMap;
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (urlConnection != null) {
urlConnection.disconnect();
}
}
return null;
}
}

错误3:运行异常 at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork
原因:Android 3.0之后不运行主线程访问网络,需另起线程访问。

 

posted @ 2018-08-21 14:19  Reboost  阅读(409)  评论(0编辑  收藏  举报