1),利用httpclient4.× 写一个http的客户端,模拟浏览器请求,
uri是请求的地址,charset是编码“UTF-8”,List<NameValuePair>就是表单参数集
2) 采用JDK的HttpConnection构造http客户端,
addPair方法:
- publicvoidpost(List<NameValuePair>payload)throwsException{
- HttpPostpost=newHttpPost(uri);
- HttpEntityresult=null;
- try{
- UrlEncodedFormEntityentity=newUrlEncodedFormEntity(payload,
- charset);
- post.setEntity(entity);
- if(LOG.isDebugEnabled()){
- LOG.debug("sending:"+payload);
- }
- HttpResponseresponse=_httpClient.execute(post);
- StatusLinestatusLine=response.getStatusLine();
- if(statusLine.getStatusCode()!=HttpStatus.SC_OK){
- result=response.getEntity();
- StringBuildermsg=newStringBuilder();
- msg.append("httpresponsewithcode"
- +statusLine.getStatusCode());
- msg.append("\n");
- msg.append("postrequest:"+post.getURI());
- msg.append("\n");
- msg.append(statusLine.getReasonPhrase());
- if(result!=null){
- msg.append("\n\n");
- msg.append(EntityUtils.toString(result,"UTF-8"));
- msg.append("\n\n");
- }
- thrownewUmcException(msg.toString());
- }
- if(response.getEntity()!=null){
- BufferedReaderreader=newBufferedReader(
- newInputStreamReader(
- response.getEntity().getContent(),"UTF-8"));
- Stringline=null;
- while((line=reader.readLine())!=null){
- if(line.indexOf("success")<0)
- System.out.println(line);
- }
- }
- }finally{
- if(result!=null)
- try{
- EntityUtils.consume(result);
- }catch(IOExceptione){
- }
- post.abort();
- }
- }
uri是请求的地址,charset是编码“UTF-8”,List<NameValuePair>就是表单参数集
- ClientConnectionManagerccManager=newThreadSafeClientConnManager();
- HttpClient_httpClient=newDefaultHttpClient(ccManager);
2) 采用JDK的HttpConnection构造http客户端,
- ////发送
- HttpURLConnectionconn=null;
- try{
- URLurl=newURL(Your_URL);
- conn=(HttpURLConnection)url.openConnection();
- conn.setRequestMethod("POST");
- conn.setRequestProperty("Content-Type",
- "application/x-www-form-urlencoded");
- conn.setUseCaches(false);
- conn.setDoOutput(true);
- OutputStreamWriterosw=newOutputStreamWriter(
- conn.getOutputStream());
- StringBuffersb=newStringBuffer();
- addPair(sb,"p1","p1value");
- addPair(sb,"p2","p2value");
- osw.write(sb.substring(0,sb.length()-1));
- osw.flush();
- BufferedReaderreader=newBufferedReader(
- newInputStreamReader(conn.getInputStream()));
- Stringline=null;
- sb=newStringBuffer();
- while((line=reader.readLine())!=null){
- sb.append(line);
- }
- line=sb.toString();
- //处理返回的字符串line
- return;
- ////
- }catch(IOExceptione){
- //handlee
- }finally{
- if(conn!=null)
- conn.disconnect();
- }///发送结束
addPair方法:
- publicstaticvoidaddPair(StringBuffersb,Stringname,Stringvalue){
- if(value==null){
- return;
- }
- sb.append(name);
- sb.append("=");
- sb.append(value);
- sb.append("&");
- }