我正在尝试将用户信息上传到服务器。我可以上传图片。但那时我无法附上用户详细信息。我正在使用以下代码上传图片。那么如何将用户详细信息添加到服务器?
try
{
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
URL url = new URL(urlServer);
connection = (HttpURLConnection) url.openConnection();
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"userfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
String serverResponseMessage = connection.getResponseMessage();
System.out.println(serverResponseCode);
System.out.println(serverResponseMessage);
fileInputStream.close();
outputStream.flush();
outputStream.close();
}
catch (Exception ex)
{
//Exception handling
}
答案 0 :(得分:2)
将您的信息捆绑在一起,并使用网址附加这些信息:
public String makeUrl(String url, Bundle params, Context context) {
url = yourBaseURL + url + "?" + encodeUrl(params);
Log.d("my url is", " URL: " + url);
return url;
}
和编码url方法是
public String encodeUrl(Bundle parameters) {
try {
if (parameters == null) {
return "";
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (String key : parameters.keySet()) {
if (first)
first = false;
else
sb.append("&");
Log.d(key + " = ", "" + parameters.getString(key));
sb.append(URLEncoder.encode(key) + "="
+ URLEncoder.encode(parameters.getString(key)));
}
return sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
return "";
}