android json封装上传服务器,使用json将数据上传到服务器android

试试这个叫POST请求

public class SendPostRequest extends AsyncTask {

protected void onPreExecute(){}

protected String doInBackground(Void... arg0) {

try {

URL url = new URL("MY URL comes here"); // here is your URL path

JSONObject postDataParams = new JSONObject();

postDataParams.put("ID", "1");

postDataParams.put("Name", "Chetan");

Log.e("params",postDataParams.toString());

HttpURLConnection conn = (HttpURLConnection) url.openConnection();

conn.setReadTimeout(60000 /* milliseconds */);

conn.setConnectTimeout(60000 /* milliseconds */);

conn.setRequestMethod("POST");

conn.setDoInput(true);

conn.setDoOutput(true);

OutputStream os = conn.getOutputStream();

BufferedWriter writer = new BufferedWriter(

new OutputStreamWriter(os, "UTF-8"));

writer.write(getPostDataString(postDataParams));

writer.flush();

writer.close();

os.close();

int responseCode=conn.getResponseCode();

if (responseCode == HttpsURLConnection.HTTP_OK) {

BufferedReader in=new BufferedReader(new

InputStreamReader(

conn.getInputStream()));

StringBuffer sb = new StringBuffer("");

String line="";

while((line = in.readLine()) != null) {

sb.append(line);

break;

}

in.close();

return sb.toString();

}

else {

return new String("false : "+responseCode);

}

}

catch(Exception e){

return new String("Exception: " + e.getMessage());

}

}

@Override

protected void onPostExecute(String result) {

/*In result you will get your response*/

Toast.makeText(getApplicationContext(), result,

Toast.LENGTH_LONG).show();

}

}

public String getPostDataString(JSONObject params) throws Exception {

StringBuilder result = new StringBuilder();

boolean first = true;

Iterator itr = params.keys();

while(itr.hasNext()){

String key= itr.next();

Object value = params.get(key);

if (first)

first = false;

else

result.append("&");

result.append(URLEncoder.encode(key, "UTF-8"));

result.append("=");

result.append(URLEncoder.encode(value.toString(), "UTF-8"));

}

return result.toString();

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值