您的位置:首页 > 产品设计 > UI/UE

Android 开发工具类 28_sendGETRequest

2015-05-30 18:47 871 查看
以 GET 方式上传数据,小于 2K,且安全性要求不高的情况下。

package com.wangjialin.internet.userInformation.service;

import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class UserInformationService {

public static boolean save(String title, String length) throws Exception{

String path = "http://192.168.1.103:8080/ServerForGETMethod/ServletForGETMethod";
Map<String, String> params = new HashMap<String, String>();
params.put("name", title);
params.put("age", length);

return sendGETRequest(path, params, "UTF-8");
}

/**
* 发送GET请求
* @param path 请求路径
* @param params 请求参数
* @return
*/
private static boolean sendGETRequest(String path, Map<String, String> params, String encoding) throws Exception{
// http://192.178.1.103:8080/ServerForGETMethod/ServletForGETMethod?title=xxxx&length=90 StringBuilder sb = new StringBuilder(path);

if(params != null && !params.isEmpty()){
sb.append("?");
for(Map.Entry<String, String> entry : params.entrySet()){
sb.append(entry.getKey()).append("=");
sb.append(URLEncoder.encode(entry.getValue(), encoding));
sb.append("&");
}
sb.deleteCharAt(sb.length() - 1);
}
HttpURLConnection conn = (HttpURLConnection) new URL(sb.toString()).openConnection();
conn.setConnectTimeout(5000);
conn.setRequestMethod("GET");

if(conn.getResponseCode() == 200){
return true;
}
return false;
}
}


UserInformationActivity

package com.wangjialin.internet.userInformation.get;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.wangjialin.internet.userInformation.service.UserInformationService;

public class UserInformationActivity extends Activity {

private EditText titleText;
private EditText lengthText;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

titleText = (EditText) this.findViewById(R.id.title);
lengthText = (EditText) this.findViewById(R.id.length);
}

public void save(View v){
String title = titleText.getText().toString();
String length = lengthText.getText().toString();
try {
boolean result = false;

result = UserInformationService.save(title, length);

if(result){
Toast.makeText(this, R.string.success, 1).show();
}else{
Toast.makeText(this, R.string.fail, 1).show();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, R.string.fail, 1).show();
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: