80,351
社区成员
发帖
与我相关
我的任务
分享
public String get(Context context, String cookieVal, String surl,
String post,String method) throws Exception {
/**
* * 首先要和URL下的URLConnection对话。 URLConnection可以很容易的从URL得到。 *比如: // Using
* java.net.URL and //java.net.URLConnection
* */
URL url = new URL(surl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
/**
* * 然后把连接设为输出模式。URLConnection通常作为输入来使用,比如下载一个Web页。 *
* 通过把URLConnection设为输出,你可以把数据向你个Web页传送。下面是如何做:
* */
connection.setDoOutput(true); // 打开输出,向服务器输出参数(POST方式、字节)
connection.setDoInput(true);// 打开输入,从服务器读取返回数据
connection.setRequestMethod(method); // 设置登录模式为POST(字符串大写)
connection.setInstanceFollowRedirects(false);
// connection.set
connection.setRequestProperty("Cookie", cookieVal);// 设置登陆配置
// Content-Type: application/x-www-form-urlencoded
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");// 设置登陆配置
/**
* 最后,为了得到OutputStream,简单起见,把它约束在Writer并且放入POST信息中,例如: ...
*/
OutputStreamWriter out = new OutputStreamWriter(
connection.getOutputStream(), "utf-8");
out.write(post); // post的关键所在!
connection.connect();
Log.v("test", connection.getHeaderFields().toString());
// 开始GET数据
String encoding = connection.getContentEncoding();
InputStream is = connection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(is, "utf-8"));
String ss = null;
String total = "";
while ((ss = bufferedReader.readLine()) != null) {
total += ss;
Log.v("test", ss);
}
bufferedReader.close();
return total;
}