用apache http-client项目进行http请求发送

发送get请求,参数放在url后面

public void addNewsChannel() throws URISyntaxException, ClientProtocolException, IOException{
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet();
		String uniqueName="bbbbbb";
		String name="hhhttt";
		String subject="课文";
		String description="描述";
		String icon = "图标";
		String params="name="+name+"&subject="+subject+"&uniqueName="+uniqueName+"&description="+description+"&icon="+icon;
		get.setURI(new URI("http://localhost:8080/appVersionVali/bcast/bcast.adb?"+params));
		HttpResponse response = client.execute(get);
		HttpEntity entity = response.getEntity();
		System.out.println(EntityUtils.toString(entity));
	}

发送post请求,上传文件到服务器,附带其他字符串


public void postUpload() throws ClientProtocolException, IOException{
		
		HttpClient httpClient = new DefaultHttpClient();
		String filename="1.jpg";
		FileBody bin = new FileBody(new File("D:"+File.separator+"img"+File.separator+filename));
		StringBody body = new StringBody("hello world",Charset.forName("utf-8"));
		
		MultipartEntity entity = new MultipartEntity();
		entity.addPart("myfile", bin);//file1为请求后台的File upload;属性  
		entity.addPart("world", body);
		
		String url="http://localhost:8080/appVersionVali/httppost";
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(entity);
		HttpResponse response = httpClient.execute(httpPost);
		int statusCode= response.getStatusLine().getStatusCode();
		System.out.println(statusCode);
		if(statusCode==HttpStatus.SC_OK){
            HttpEntity resEntity = response.getEntity();  
            System.out.println(EntityUtils.toString(resEntity));//httpclient自带的工具类读取返回数据  
            System.out.println(resEntity.getContent());     
            EntityUtils.consume(resEntity);  
		}
		httpClient.getConnectionManager().shutdown();
	}

发送post请求,发送表单到服务器

HttpClient httpClient = new DefaultHttpClient();
		String uniqueName="cccccc";
		String name="hhhttt";
		String subject="课文";
		String description="描述";
		String icon = "图标";
		List<NameValuePair>list = new ArrayList<NameValuePair>();
		list.add(new BasicNameValuePair("uniqueName", uniqueName));
		list.add(new BasicNameValuePair("name", name));
		list.add(new BasicNameValuePair("subject", subject));
		list.add(new BasicNameValuePair("description", description));
		list.add(new BasicNameValuePair("icon", icon));
		UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(list,Charset.forName("utf-8"));
		HttpPost httpPost = new HttpPost(new URI("http://localhost:8080/appVersionVali/bcast/bcast.adb"));
		httpPost.setEntity(encodedFormEntity);
		HttpResponse response = httpClient.execute(httpPost);
		String content = EntityUtils.toString(response.getEntity());
		System.out.println(content);
		httpClient.getConnectionManager().shutdown();


你可能感兴趣的:(用apache http-client项目进行http请求发送)