暂存一下代码,以后有时间来好好总结一下这块。
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
post("http://upload.img.go-friends.com.cn/upload.php");
}
}).start();
}
public void post(String string){
Resources res=getResources();
Bitmap bitmap=BitmapFactory.decodeResource(res, R.drawable.imagea);
byte[] b = getImageBytes(bitmap);
URL url = null;
try {
url = new URL(string);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setConnectTimeout(3000); //设置连接超时时间
httpURLConnection.setDoInput(true); //打开输入流,以便从服务器获取数据
httpURLConnection.setDoOutput(true); //打开输出流,以便向服务器提交数据
httpURLConnection.setRequestMethod("POST"); //设置以Post方式提交数据
httpURLConnection.setUseCaches(false); //使用Post方式不能使用缓存
//设置请求体的类型是文本类型
httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
//设置请求体的长度
httpURLConnection.setRequestProperty("Content-Length", String.valueOf(b.length));
//获得输出流,向服务器写入数据
OutputStream outputStream = httpURLConnection.getOutputStream();
outputStream.write(b);
int response = httpURLConnection.getResponseCode(); //获得服务器的响应码
if(response == HttpURLConnection.HTTP_OK) {
InputStream inptStream = httpURLConnection.getInputStream();
System.out.println(dealResponseResult(inptStream)); //处理服务器的响应结果
}
} catch (IOException e) {
e.printStackTrace();
}
}
private byte[] getImageBytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
public String dealResponseResult(InputStream inputStream) {
String resultData = null; // 存储处理结果
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] data = new byte[1024];
int len = 0;
try {
while ((len = inputStream.read(data)) != -1) {
baos.write(data, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
resultData = new String(baos.toByteArray());
return resultData;
}
}