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之后不运行主线程访问网络,需另起线程访问。

 

转载于:https://www.cnblogs.com/reboost/p/9510938.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值