javahttp上传图片
㈠ 如何来 发送HTTP请求GET / POST在java中
在Java中发送HTTP请求,主要涉及到请求行的构建。请求行由三个部分组成:请求方法字段、URL字段和HTTP协议版本字段,这三个字段之间用空格分隔。例如,使用GET方法访问某个HTML页面时,请求行可以表示为"GET /index.html HTTP/1.1"。这里,"GET"是请求方法,"/index.html"是访问的资源路径,而"HTTP/1.1"则指定了使用的HTTP版本。
除了GET方法外,HTTP协议还支持其他几种请求方法,包括POST、HEAD、PUT、DELETE、OPTIONS、TRACE和CONNECT。其中,POST方法通常用于向服务器发送数据,例如提交表单或上传文件;而HEAD方法则只获取响应头,不获取响应体;PUT方法用于上传数据到服务器,相当于文件上传;DELETE方法则是用于删除服务器上的资源;OPTIONS方法用于获取服务器的许可信息,如支持的请求方法;TRACE方法用于回显客户端发送的请求,主要用于诊断;而CONNECT方法则是用于建立代理连接。
Java中发送HTTP请求的方法有很多,比如使用HttpURLConnection类或第三方库如Apache HttpClient和OkHttp。以HttpURLConnection为例,首先需要创建一个URL对象,然后通过该对象获取HttpURLConnection实例,接下来设置请求方法、添加请求头等,最后执行请求并获取响应。而使用第三方库时,初始化和设置则更加灵活,可以根据需求选择合适的库进行操作。
对于GET请求,HttpURLConnection的使用相对简单。以下是一个使用HttpURLConnection发送GET请求的例子:
java
URL url = new URL("http://example.com/index.html");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
System.out.println(response.toString());
} else {
System.out.println("Failed : HTTP error code : " + responseCode);
}
通过这段代码,你可以看到如何通过HttpURLConnection发送GET请求并处理响应。当然,实际应用中可能还需要处理更复杂的情况,比如添加请求头、处理异常等。
对于POST请求,基本步骤类似,只是需要设置请求方法为POST,并且通常需要设置请求体。以下是一个简单的POST请求示例:
java
URL url = new URL("http://example.com/post");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String data = "param1=value1¶m2=value2";
try (DataOutputStream wr = new DataOutputStream(connection.getOutputStream())) {
wr.writeBytes(data);
}
这段代码展示了如何通过HttpURLConnection发送POST请求,并设置请求体。同样,实际应用中可能需要添加更多细节,如处理响应、添加更多请求头等。
总之,Java中发送HTTP请求GET和POST方法的实现方式多样,可以根据具体需求选择合适的库和方法。无论使用哪种方式,都需要正确设置请求方法、URL、请求头等,才能确保请求的成功发送和响应的正确处理。
㈡ 请教各位问题:java web客户端上传图片到服务器的D盘下,请问客户端怎么通过http访问图片
如果想让tomcat服务器访问指定磁盘 上的静态资源,可在tomcat/conf/server.xml中查找<Host></Host>,在标签中添加如下标签<Context path="/file" docBase="D:/img" reloadable="true"/>,再通过localhost:8080/file地址来访问路境内的文件:
如要访问名为d:/img/cat.png的图片,则localhost:8080/file/cat.png
㈢ java http post 怎么设置 raw格式
调试微信推广支持中二维码生成api的接口,使用chrome浏览器的postman插件,post请求时有一个选项是form-data,或者raw,使用raw可以请求成功,from-data不知道怎么组装key和value所以一直失败。非常不明白raw是什么意思,google网络都没有相关的解释。后来研究发现,其实raw方式使用的是纯字符串的数据上传方式,所以在POST之前,可能需要手工的把一些json/text/xml格式的数据转换成字符串,是一种post原始请求,区别于form-data这种常用的key-value方式。
public static String result; public static void httpTest() throws ClientProtocolException, IOException { String token = "XRhjxAJZG3rFlPLg"; String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + token; String json = "{"action_name":"QR_LIMIT_SCENE","action_info":{"scene":{"scene_id":234}}}"; HttpClient httpClient = new DefaultHttpClient(); HttpPost post = new HttpPost(url); StringEntity postingString = new StringEntity(json);// json传递 post.setEntity(postingString); post.setHeader("Content-type", "application/json"); HttpResponse response = httpClient.execute(post); String content = EntityUtils.toString(response.getEntity()); // Log.i("test",content); System.out.println(content); result = content; }
以上代码中需要导入
import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils;
Android中自带org.apache.http相关库文件,所以可以快捷键(ctrl+shift+o)一次导入成功。
㈣ Java利用HttpURLConnection发送post请求上传文件
在页面里实现上传文件不是什么难事 写个form 加上enctype = multipart/form data 在写个接收的就可以了 没租裤什么难的 如果要用 HttpURLConnection来实现文件上传 还真有点搞头 : )
先写个servlet把接收到的 HTTP 信息保存在一个文件中 看一下 form 表单到底封装了什么样的信息
Java代码
public void doPost(HttpServletRequest request HttpServletResponse response)
throws ServletException IOException {
//获取输入流 是HTTP协议中的实体内容
ServletInputStream in=request getInputStream();
//缓冲区
byte buffer[]=new byte[ ];
FileOutputStream out=new FileOutputStream( d:\test log );
int len=sis read(buffer );
//把流里的信息循环读入到file log文件中
while( len!= ){
out write(buffer len);
len=in readLine(buffer );
}
out close();
in close();
}
来一个form表单
<form name= upform action= upload do method= POST
enctype= multipart/form data >
参数<input type= text name= username /><br/>
文件 <input type= file name= file /><br/>
文件 <input type= file name= file /><br/>
<input type= submit value= Submit />
<br />
</form>
假如我参数写的内容是hello word 然后二个文件是二个简单的txt文件梁誉 上传后test log里如下
Java代码
da e c
Content Disposition: form data; name= username
hello word
da e c
Content Disposition: form data; name= file ; filename= D:haha txt
Content Type: text/plain
haha
hahaha
da e c
Content Disposition: form data; name= file ; filename= D:huhu txt
Content Type: text/plain
messi
huhu
da e c
研究下规律发现有如下几点特征
第一行是 d b bc 作为分隔符 然后是 回车换行符 这个 d b bc 分隔符浏览器是随机生成的
第二行是Content Disposition: form data; name= file ; filename= D:huhu txt ;name=对应input的name值 filename对应要上传的文件名(包括路径在内)
第三行如果是文件就有Content Type: text/plain 这里上传的是txt文件所以是text/plain 如果上穿的是jpg图片的话就是image/jpg了 可以自己试试看看
然后就是回弊渣简车换行符
在下就是文件或参数的内容或值了 如 hello word
最后一行是 da e c 注意最后多了二个 ;
有了这些就可以使用HttpURLConnection来实现上传文件功能了
Java代码 public void upload(){
List<String> list = new ArrayList<String>(); //要上传的文件名 如 d:haha doc 你要实现自己的业务 我这里就是一个空list
try {
String BOUNDARY = d a d c ; // 定义数据分隔线
URL url = new URL( );
HttpURLConnection conn = (HttpURLConnection) url openConnection();
// 发送POST请求必须设置如下两行
conn setDoOutput(true);
conn setDoInput(true);
conn setUseCaches(false);
conn setRequestMethod( POST );
conn setRequestProperty( connection Keep Alive );
conn setRequestProperty( user agent Mozilla/ (patible; MSIE ; Windows NT ; SV ) );
conn setRequestProperty( Charsert UTF );
conn setRequestProperty( Content Type multipart/form data; boundary= + BOUNDARY);
OutputStream out = new DataOutputStream(conn getOutputStream());
byte[] end_data = ( + BOUNDARY + ) getBytes();// 定义最后数据分隔线
int leng = list size();
for(int i= ;i<leng;i++){
String fname = list get(i);
File file = new File(fname);
StringBuilder *** = new StringBuilder();
*** append( );
*** append(BOUNDARY);
*** append( );
*** append( Content Disposition: form data;name= file +i+ ;filename= + file getName() + );
*** append( Content Type:application/octet stream );
byte[] data = *** toString() getBytes();
out write(data);
DataInputStream in = new DataInputStream(new FileInputStream(file));
int bytes = ;
byte[] bufferOut = new byte[ ];
while ((bytes = in read(bufferOut)) != ) {
out write(bufferOut bytes);
}
out write( getBytes()); //多个文件时 二个文件之间加入这个
in close();
}
out write(end_data);
out flush();
out close();
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(new InputStreamReader(conn getInputStream()));
String line = null;
while ((line = reader readLine()) != null) {
System out println(line);
}
} catch (Exception e) {
System out println( 发送POST请求出现异常! + e);
e printStackTrace();
}
lishixin/Article/program/Java/hx/201311/27114
㈤ 用JAVA下载HTTP文件时遇到问题
importjava.net.*;
importjava.io.*;
publicclassURLConnectionDemo{
publicstaticvoidmain(String[]args)throwsException{
URLurl=newURL("http://www.scp.e.cn/pantoschoolzz/BG/Bord/Message/DownloadMessageAttachment.aspx?ID=215");
URLConnectionuc=url.openConnection();
StringfileName=uc.getHeaderField(6);
fileName=URLDecoder.decode(fileName.substring(fileName.indexOf("filename=")+9),"UTF-8");
System.out.println("文件名为:"+fileName);
System.out.println("文件大小:"+(uc.getContentLength()/1024)+"KB");
Stringpath="D:"+File.separator+fileName;
FileOutputStreamos=newFileOutputStream(path);
InputStreamis=uc.getInputStream();
byte[]b=newbyte[1024];
intlen=0;
while((len=is.read(b))!=-1){
os.write(b,0,len);
}
os.close();
is.close();
System.out.println("下载成功,文件保存在:"+path);
}
}
//给你一个下载的例子吧,仅供参考。