Android 에서 Http 요청 인 스 턴 스 보 내기
/**
* http , ,
* @param actionUrl
* @param params key ,value
* @param file
*/
public static void postMultiParams(String actionUrl, Map<String, String> params, FormBean[] files) {
try {
PostMethod post = new PostMethod(actionUrl);
List<art> formParams = new ArrayList<art>();
for(Map.Entry<String, String> entry : params.entrySet()){
formParams.add(new StringPart(entry.getKey(), entry.getValue()));
}
if(files!=null)
for(FormBean file : files){
//filename ,filepath ( ),filebean
formParams.add(new FilePart("file", file.getFilename(), new File(file.getFilepath())));
}
Part[] parts = new Part[formParams.size()];
Iterator<art> pit = formParams.iterator();
int i=0;
while(pit.hasNext()){
parts[i++] = pit.next();
}
//
//StringPart sp = new StringPart("TEXT", "testValue", "GB2312");
//FilePart fp = new FilePart("file", "test.txt", new File("./temp/test.txt"), null, "GB2312"
//postMethod.getParams().setContentCharset("GB2312");
MultipartRequestEntity mrp = new MultipartRequestEntity(parts, post.getParams());
post.setRequestEntity(mrp);
//execute post method
HttpClient client = new HttpClient();
int code = client.executeMethod(post);
System.out.println(code);
} catch ...
}
java post ,
java main :
public static void main(String[] args){
String actionUrl = "http://192.168.0.123:8080/WSserver/androidUploadServlet";
Map<String, String> strParams = new HashMap<String, String>();
strParams.put("paramOne", "valueOne");
strParams.put("paramTwo", "valueTwo");
FormBean[] files = new FormBean[]{new FormBean("dest1.xml", "F:/testpostsrc/main.xml")};
HttpTool.postMultiParams(actionUrl,strParams,files);
}
, android , 。
PostMethod ,org.apache.commons.httpclient.methods.PostMethod ;
VerifyError。 , SDK , ~~
http request post , , , java post , servlet , ! :
***********************************************************
/**
* ,
* @param actionUrl
* @param params
* @param files
* @return
* @throws IOException
*/
public static String post(String actionUrl, Map<String, String> params,
Map<String, File> files) throws IOException {
String BOUNDARY = java.util.UUID.randomUUID().toString();
String PREFIX = "--" , LINEND = "\r
";
String MULTIPART_FROM_DATA = "multipart/form-data";
String CHARSET = "UTF-8";
URL uri = new URL(actionUrl);
HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
conn.setReadTimeout(5 * 1000); //
conn.setDoInput(true);//
conn.setDoOutput(true);//
conn.setUseCaches(false); //
conn.setRequestMethod("POST");
conn.setRequestProperty("connection", "keep-alive");
conn.setRequestProperty("Charsert", "UTF-8");
conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY);
//
StringBuilder sb = new StringBuilder();
for (Map.Entry<String, String> entry : params.entrySet()) {
sb.append(PREFIX);
sb.append(BOUNDARY);
sb.append(LINEND);
sb.append("Content-Disposition: form-data; name=\"" + entry.getKey() + "\"" + LINEND);
sb.append("Content-Type: text/plain; charset=" + CHARSET+LINEND);
sb.append("Content-Transfer-Encoding: 8bit" + LINEND);
sb.append(LINEND);
sb.append(entry.getValue());
sb.append(LINEND);
}
DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
outStream.write(sb.toString().getBytes());
//
if(files!=null)
for (Map.Entry<String, File> file: files.entrySet()) {
StringBuilder sb1 = new StringBuilder();
sb1.append(PREFIX);
sb1.append(BOUNDARY);
sb1.append(LINEND);
sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getKey()+"\""+LINEND);
sb1.append("Content-Type: application/octet-stream; charset="+CHARSET+LINEND);
sb1.append(LINEND);
outStream.write(sb1.toString().getBytes());
InputStream is = new FileInputStream(file.getValue());
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
is.close();
outStream.write(LINEND.getBytes());
}
//
byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
outStream.write(end_data);
outStream.flush();
//
int res = conn.getResponseCode();
if (res == 200) {
InputStream in = conn.getInputStream();
int ch;
StringBuilder sb2 = new StringBuilder();
while ((ch = in.read()) != -1) {
sb2.append((char) ch);
}
}
outStream.close();
conn.disconnect();
return in.toString();
}
**********************
button :
**********************
public void onClick(View v){
String actionUrl = getApplicationContext().getString(R.string.wtsb_req_upload);
Map<String, String> params = new HashMap<String, String>();
params.put("strParamName", "strParamValue");
Map<String, File> files = new HashMap<String, File>();
files.put("tempAndroid.txt", new File("/sdcard/temp.txt"));
try {
HttpTool.postMultiParams(actionUrl, params, files);
} catch ...
***************************
servlet :
***************************
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//print request.getInputStream to check request content
//HttpTool.printStreamContent(request.getInputStream());
RequestContext req = new ServletRequestContext(request);
if(FileUpload.isMultipartContent(req)){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
fileUpload.setFileSizeMax(FILE_MAX_SIZE);
List items = new ArrayList();
try {
items = fileUpload.parseRequest(request);
} catch ...
Iterator it = items.iterator();
while(it.hasNext()){
FileItem fileItem = (FileItem)it.next();
if(fileItem.isFormField()){
System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+new String(fileItem.getString().getBytes("ISO-8859-1"),"GBK"));
} else {
System.out.println(fileItem.getFieldName()+" "+fileItem.getName()+" "+
fileItem.isInMemory()+" "+fileItem.getContentType()+" "+fileItem.getSize());
if(fileItem.getName()!=null && fileItem.getSize()!=0){
File fullFile = new File(fileItem.getName());
File newFile = new File(FILE_SAVE_PATH+fullFile.getName());
try {
fileItem.write(newFile);
} catch ...
} else {
System.out.println("no file choosen or empty file");
}
}
}
}
}
public void init() throws ServletException {
// web.xml init-param
FILE_MAX_SIZE = Long.parseLong(this.getInitParameter("file_max_size"));//
FILE_SAVE_PATH = this.getInitParameter("file_save_path");//
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자바 파일 압축 및 압축 풀기파일 의 간단 한 압축 과 압축 해 제 를 실현 하 였 다.주요 테스트 용 에는 급 하 게 쓸 수 있 는 부분 이 있 으 니 불편 한 점 이 있 으 면 아낌없이 가르쳐 주 십시오. 1. 중국어 문 제 를 해 결 했 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.