80,355
社区成员
发帖
与我相关
我的任务
分享
private String toRegist(String phone,String phoneCode,String password) {
HttpURLConnection conn = null;
PrintWriter printWriter = null;
BufferedReader bufferedReader = null;
StringBuffer responseResult = new StringBuffer();
try {
String newUrl = URL +"?phone="+ phone + "&phoneCode=" + phoneCode + "&password=" + password;
URL url = new URL(newUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 提交模式
conn.setRequestProperty("Content-Type", "plain/text; charset=UTF-8");
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.connect();
// 根据ResponseCode判断连接是否成功
int responseCode = conn.getResponseCode();
if (responseCode != 200) {
System.out.println("Not Success");
} else {
System.out.println("Success");
}
// 定义BufferedReader输入流来读取URL的ResponseData
bufferedReader = new BufferedReader(new InputStreamReader(
conn.getInputStream()));
String line;
while ((line = bufferedReader.readLine()) != null) {
responseResult.append(line);
}
/* 关闭DataOutputStream */
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
conn.disconnect();
try {
if (printWriter != null) {
printWriter.close();
}
if (bufferedReader != null) {
bufferedReader.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return responseResult.toString();
}
printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(params.toString());
// flush输出流的缓冲
printWriter.flush();
这样,每到返回操作码的时候都会是404,因为没辙所以才直接拼接在地址栏上,请问,你有啥好的办法么?[/quote]
/**
* 通过HttpURLConnection模拟post表单提交
*
* @param path
* @param params 例如"name=zhangsan&age=21"
* @return
* @throws Exception
*/
public static byte[] sendPostRequestByForm(String path, String params) throws Exception{
URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");// 提交模式
// conn.setConnectTimeout(10000);//连接超时 单位毫秒
// conn.setReadTimeout(2000);//读取超时 单位毫秒
conn.setDoOutput(true);// 是否输入参数
byte[] bypes = params.toString().getBytes();
conn.getOutputStream().write(bypes);// 输入参数
InputStream inStream=conn.getInputStream();
return StreamTool.readInputStream(inStream);
}
printWriter = new PrintWriter(httpURLConnection.getOutputStream());
// 发送请求参数
printWriter.write(params.toString());
// flush输出流的缓冲
printWriter.flush();
这样,每到返回操作码的时候都会是404,因为没辙所以才直接拼接在地址栏上,请问,你有啥好的办法么?